package com.example.njupt.okhttp;

import android.util.Log;

import com.example.njupt.log.NjuptLogger;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * Author:      mwang
 * Create Date: Created in 2021/5/27 15:46
 * Update Date:
 * Modified By:
 * Description: 日志管理
 */
public class RetrofitInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        long requestTime = System.currentTimeMillis();

        synchronized (RetrofitInterceptor.class) {
            new NjuptLogger().iTag("httpRequest", request.method() + " ===> " + request.url());
            new NjuptLogger().iTag("httpRequest", String.valueOf(request.headers()));
            if (null != request.body()) {
                Buffer buffer = new Buffer();
                request.body().writeTo(buffer);
                Log.d("httpRequest", buffer.readUtf8());
            }
        }

        Response response = chain.proceed(request);
        long responseTime = System.currentTimeMillis();
        ResponseBody responseBody =  response.peekBody(1024 * 1024);

        synchronized(RetrofitInterceptor.class) {
            new NjuptLogger().iTag("httpResponse", response.request().method() + "\t" + response.code() + " <=== " + response.request().url() + "\t" + (responseTime - requestTime) + "ms");
            new NjuptLogger().iTag("httpResponse", responseBody.string());
        }
        return response;
    }
}
